package com.liu.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.liu.entity.Working;
import com.liu.entity.WorkingLite;
import com.liu.service.WorkingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Controller
public class WorkingController {
    private WorkingService workingService;
    @Autowired
    public void setWorkingService(WorkingService workingService) {
        this.workingService = workingService;
    }
    @RequestMapping("/getAll")
    public String getAll(Model model){
        List<Working> list = workingService.getAll();
        model.addAttribute("allInfo",list);
        return "index";
    }
    @RequestMapping("/getByID/{id}")
    public String getByID(@PathVariable int id,Model model){
        Working working = workingService.getInfoByID(id);
        model.addAttribute("working",working);
        return "myWorking";
    }
    @RequestMapping("/toAddPage")
    public String toAdd(){
        return "addWorking";
    }

    @RequestMapping("/getByTitle")
    @ResponseBody
    public String getByTitle(String title){
        int infoByTitle = workingService.getInfoByTitle(title);
        if (infoByTitle>0){
            return "fail";
        }else{
            return "success";
        }
    }

    @RequestMapping("/addInfo")
    @ResponseBody
//    如果前端传过来的是json
    public String addInfo(@RequestBody String workingStr, Model model){
        //可以通过fastJson把json字符串转成java对象
        JSONObject jb = JSONObject.parseObject(workingStr);
        int i = workingService.addInfo(JSON.toJavaObject(jb, Working.class));
        if (i>0){
            return "success";
        }else {
            return "fail";
        }
    }
}
